<?php

/**
 * @category   Ac
 * @package    Ad
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     Olivier Bregeras
 */
class Listing_MobileController extends Ac_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->_helper->layout->setLayout('layout-mobile2');
        
    }

    public function indexAction()
    {
        // action body
    }

    public function displayAction()
    {
       // $this->_helper->_layout->setLayout('ad-details-layout');
       
       

		$this->view->module_content = "search";
        $params = $this->_request->getParams();

        $listing = Model_Listing::find(new MongoId($params['id']));

        if ($listing == null) {// listing not found
            throw new Ac_Exception_MissingListing('not found');
        }
        if (empty($this->loggedin_user) && $listing->status !== Model_Listing::STATUS_PUBLISHED) {
            throw new Ac_Exception_MissingListing('draft - user not logged in');
        }
        
        if (!empty($this->loggedin_user) && 
            ($listing->status !== Model_Listing::STATUS_PUBLISHED && 
                (string) $listing->user->_id !== (string)$this->loggedin_user->_id
            )
        ){
            throw new Ac_Exception_MissingListing('draft - not belonging to user');
        }
        
        Model_History::addMobileListing($listing->_id);
        $to_add = '';
        if ((string) $listing->category[0]->path[0] == '4cda3e818835c16810770100') { //mc56 Pets
            $to_add = $listing->category[0]->name . ' - ';
        }
       //add header for facebook
        $this->view->headMeta()->appendName('og:type', 'product');
        if (!empty($listing->title)) {
            $this->view->headMeta()->appendName('og:title', $to_add . ' - ' . $listing->title);
        }
        if (!empty($listing->description)) {
            $this->view->headMeta()->appendName('og:description', substr($listing->description, 0, 100));
            $this->view->headMeta()->appendName('description', substr($listing->description, 0, 100));
        }
        $this->view->headMeta()->appendName('keywords', $to_add . implode(', ', $listing->getKeyword()));
        $this->view->headMeta()->appendName('og:url', $listing->url(true));
        if (!empty($listing->longitude)) {
            $this->view->headMeta()->appendName('og:longitude', $listing->longitude);
        }
        if (!empty($listing->latitude)) {
            $this->view->headMeta()->appendName('og:latitude', $listing->latitude);
        }
        if (!empty($listing->photos[0])) {
            $this->view->headMeta()->appendName('og:image', $this->view->thumbnail()->resizeAndCrop($listing->photos[0], 130, 110));
        }

        //$this->_title[] = $listing->title;
        $this->addTitle($to_add . $listing->title);
        $this->setCanonical($listing->url());
		
        //be sure that the title provided is the right one
        //if (trim($params['title']) != $listing->title_url) {
        //if (urldecode(trim($params['title'])) != trim(urldecode($listing->title_url))) {
        if (preg_replace('#\v#', '', urldecode(trim($params['title']))) != preg_replace('#\v#', '', trim(urldecode($listing->title_url)))) {
            $this->_redirect($listing->url(), array('code' => 301));
        }
        
        $config = array('listing' => $listing);
        if (!empty($this->loggedin_user->_id)) {
            $config['user'] = $this->loggedin_user;
        }
        $form = new Listing_Form_SendMessageMobileForm($config);
        
        if (!empty($_GET['sid'])) {
            $this->view->search = Model_Search::find($_GET['sid']);
        }

        if ($this->_request->isPost() && $form->isValid($_POST)) {
        //if ($this->_request->isPost()) {
            //save email send to
            $session = new Zend_Session_Namespace('send_message');
            $tmp = array();
            $tmp[(string)$listing->_id] = $_POST['newmessage']['email'];
            $session->listing = $tmp;
            $form->save();
            $this->_redirect($this->view->geturl('send-message', 'listing', null, null, array('id' => (string)$listing->_id, 'sid' => !empty($_GET['sid'])?$_GET['sid']:'')));
        }
        
        if($listing->sold){
			$this->view->similar_ads_user = $listing->findRelated(3, Model_Listing::RELATED_SAME_TITLE + Model_Listing::RELATED_SAME_USER);
            if (empty($this->view->similar_ads_user)) {
                $this->view->similar_ads_user = $listing->findRelated(3, Model_Listing::RELATED_SAME_USER);
            }
            $this->view->similar_ads_other = $listing->findRelated(6, Model_Listing::RELATED_SAME_TITLE);
            if (empty($this->view->similar_ads_other)) {
                $this->view->similar_ads_other = $listing->findRelated(6, Model_Listing::RELATED_SAME_CATEGORY);
            }
		}
        
        //load bookmark
        $list = Model_Bookmark::getList();
        $bookmark = array();
        if (!empty($list)) {
            foreach($list as $bmk) {
                if (!empty($bmk->listing)) {
                    $bookmark[] = (string) $bmk->listing->_id;
                }
            }
        }
        $this->view->bookmark = $bookmark;
        
        if (!empty($listing->category[0]) && !empty($listing->category[0]->path[0])) {
            Zend_Registry::set('main_category', Model_Category::find($listing->category[0]->path[0]));
        }
        
        $listing->newView();
        $this->view->send_message_form = $form;
        $this->view->listing           = $listing;
        
        $this->render('details');
    }

    public function sendMessageAction()
    {
    	$this->view->module_content = "search";
        $listing = Model_Listing::find(new MongoId($_GET['id']));
        
        if(empty($listing)) {
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect('/');
        }        
        $this->view->listing = $listing;
        $session = new Zend_Session_Namespace('send_message');
        $this->view->email = $session->listing[$_GET['id']];

        $solr = Ac_Search::getClient();
        $query = '*:*';

        $additionalParameters = array();
        $fq='+status:1 ';
        foreach ($listing->category as $cat) {
            $fq .= ' +category:' . (string)$cat->_id;
        }
        if (!empty($listing->area_l2) && !empty($listing->area_l2)) {
            $fq .= ' +area_l2:' . (string)$listing->area_l2->_id;
        }
        $additionalParameters['fq']   = $fq;
        $additionalParameters['sort'] = 'random_'.rand(1, 10000).' desc';

        $list = $solr->search($query, 1, 6, $additionalParameters);
        $this->view->similar_ads = $list->response->docs;
        
        if (!empty($_GET['sid'])) {
            $this->view->search = Model_Search::find($_GET['sid']);
        }
    }

    public function validateSendMessageAction()
    {
        $form = new Listing_Form_SendMessageForm();
        //unset($_POST['newmessage']['captcha']);
        $form->isValidPartial($_POST);
        $this->_helper->json($form->getMessages());
    }

    public function previewAction()
    {
        
        if (empty($_POST['category'])) {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing', null, null, array('error' => 1)));
        }

        $this->_helper->_layout->setLayout('login-layout');
        $session = new Zend_Session_Namespace('post-an-ad');

        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }
        //var_dump($_GET, $_SESSION);exit;
        $session = new Zend_Session_Namespace('post-an-ad');
        //$session->unsetAll();
        //var_dump($_POST, $_SESSION);exit;


        if (!empty($_POST['adid'])) {
            $u         = Model_Listing_Preview::find($_POST['adid']);
            if (empty($u)) {
                $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
            }
        } else{
            $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
        }
        
        
        $category = array();
        foreach((array) $_POST['category'] as $cat_id) {
            if (!empty($cat_id)) {
                $u->addCategory($cat_id);
            }
        }
        
        $options                 = array();
        $options['adid']         = (string) $u->_id;
        $options['listing']      = $u;
        $form = $u->postAnAddForm($options);

        $form->populate((array)$_POST);
        $listing = $form->save(true);//preview mode

        $this->view->mode    = 'preview';
        $this->view->listing = $listing;
        //$this->render('display');
    }

    public function editAction()
    {
        //$session = new Zend_Session_Namespace('post-an-ad');
        //$session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        //$ad = Model_Listing_Preview::convertFromListing($ad);
        //$ad->save();
        //$ad->photos_tmp = $ad->photos;
        if ($ad instanceof Model_Listing_Regular) {
            $session = new Zend_Session_Namespace('post-an-ad');
            $session->listing_started = $_GET['id'];
        }

        foreach ($ad->category as $cat) {
            $_GET['category'][] = (string) $cat->_id;
        }
        return $this->_forward('post-an-add-information');
    }

    public function postAnAddInformationAction()
    {
        /*
        if ($this->_request->isGet()) {
            $this->_redirect($this->view->geturl('post-an-ad','listing'));
        }*/
        
        
        if (empty($_GET['category'])) {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing', null, null, array('error' => 1)));
        }

        $this->_helper->_layout->setLayout('login-layout');
        $session = new Zend_Session_Namespace('post-an-ad');
        
        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }
        
        //var_dump($_GET, $_SESSION);exit;
        $session = new Zend_Session_Namespace('post-an-ad');
        //$session->unsetAll();
        //var_dump($_GET, $_SESSION);exit;
        
        //Edit
        if (!empty($_GET['id']) && $this->_request->isGet()) {
            $classname = Model_Listing::getInstanceClassname((array)$_GET['category']);
            $u         = Model_Listing::getInstance($classname, $_GET['id']);
            $u         = Model_Listing_Preview::convertFromListing($u);
        } elseif (!empty($_GET['id']) && $this->_request->isPost()) {
            $classname = Model_Listing::getInstanceClassname((array)$_POST['category']);
            $u         = Model_Listing_Preview::getInstance($classname, $_GET['id']);

           //echo '<pre>';print_r($u);exit;
        } else if (!empty($session->listing_started)) {
            $classname = Model_Listing::getInstanceClassname((array)$_GET['category']);
            $u         = Model_Listing_Preview::getInstance($classname, $session->listing_started);
            if (empty($u)) {
                $u = Model_Listing::getInstance($classname, $session->listing_started);
            }
        } else{
            $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
        }

        
        //var_dump($session->listing_started, (string) $u->_id);
        $category = array();
        if (!empty($_GET['category'])) {
            $u->ca = array();
            foreach((array)$_GET['category'] as $cat_id) {
                if (!empty($cat_id)) {
                    $u->addCategory($cat_id);
                }
            }
        }

        //if default photo uploader used
        
        //var_dump($_FILES);exit;
        if ($this->_request->isPost() && !empty($_FILES)) {
            //move_uploaded_file($_FILES['upload1']['tmp_name'], '/tmp/test.jpg');
            //var_dump($_FILES, is_uploaded_file($_FILES['upload1']['tmp_name']));exit;
            $_SERVER['HTTP_ADID'] = $u;
            $_SERVER['NOT_JSON'] = 1;
            $res = Ac_Util::uploadListingPhotoProcess();
            //var_dump($res);exit;
        }        
        
        $options                 = array();
        $options['preview_link'] = $this->view->geturl('preview', 'listing');
        $options['adid']         = (string) $u->_id;
        $options['listing']      = $u;
        $form = $u->postAnAddForm($options);

        $form->populate((array)$_POST);
        /*
var_dump($this->_request->isPost(), 
                $form->isValid($_POST),
                    !empty($this->loggedin_user), $this->loggedin_user->role == Model_User::ROLE_ADMIN, ($this->_request->isPost() && 
                ($form->isValid($_POST) || 
                    (!empty($this->loggedin_user) && $this->loggedin_user->role == Model_User::ROLE_ADMIN))));exit;
         * 
         */
        if ($this->_request->isPost() && 
                ($form->isValid($_POST) || 
                    (!empty($this->loggedin_user) && $this->loggedin_user->role == Model_User::ROLE_ADMIN))) {
        //if ($this->_request->isPost()) {
            $ad = $form->save();
            
            $_POST = array();
            $session->unsetAll();
            if (Zend_Registry::isRegistered('loggedin_user')) {
                //$this->_redirect($ad->url());
                if (!empty($_GET['id'])) {
                    if ($this->loggedin_user->role == Model_User::ROLE_ADMIN && (string) $ad->user->_id != (string) $this->loggedin_user->_id) {
                        $this->_redirect($ad->url());
                    } else {
                        $this->_redirect($this->view->geturl('my-account-ads', 'user'));
                    }
                }else {
                    $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                    $to_be_confirmed_ads->setExpirationSeconds(10000000);
                    $arr = (array)$to_be_confirmed_ads->arr;
                    $arr[] = $ad->_id;
                    $to_be_confirmed_ads->arr = $arr;
                    $to_be_confirmed_ads->lock();
                    $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('loggedin' => 1, 'return'=> (string) $ad->_id, 'login_process' => 1)));
                }
                
            } else {
                //redirect to register the user
                //save $ad id as a cookie or permanent session

                $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                $to_be_confirmed_ads->setExpirationSeconds(10000000);
                $arr = (array)$to_be_confirmed_ads->arr;
                $arr[] = $ad->_id;
                $to_be_confirmed_ads->arr = $arr;
                $to_be_confirmed_ads->lock();
                //echo '<pre>';print_r($_SESSION);exit;
                $this->_redirect($this->view->geturl('login', 'user', null, null, array('return'=> (string) $ad->_id)));
            }
        }

        $this->view->category = $u->getCategory();
        $this->view->form = $form;
        $this->render('post-an-ad-info');
    }

    public function postAnAdAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        if(!empty($_GET['change']) && !empty($session->listing_started)) {
            $ad = Model_Listing_Preview::one(array('_id' => new MongoId($session->listing_started)));
            if (empty($ad)) {
                $ad = new Model_Listing_Preview();
                $ad->status = Model_Listing::STATUS_STARTED;
                $ad->save();
            }
        } else {
            $ad = new Model_Listing_Preview();
            $ad->status = Model_Listing::STATUS_STARTED;
            $ad->save();
        }

        if(!empty($_GET['category'])) {
            $tmp = array();
            foreach((array) $_GET['category'] as $cat) {
                $tmp[] = Model_Category::find($cat);
            }
            $this->view->selected_category  = $tmp;
        }
        
        $session->setExpirationSeconds(10*365*24*3600); //10 years
        $session->listing_started = (string) $ad->_id;
        $this->_helper->_layout->setLayout('login-layout');

        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }
        if (!empty($_GET['change'])) {
            $this->view->listing = $ad;
        }

        $this->view->level1 = Model_Category::getLevel1(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array( 'pos' => 1));
        $this->view->level2 = Model_Category::getLevel2(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array( 'path.0'=>1, 'pos' => 1));
        $this->view->level3 = Model_Category::getLevel3(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array( 'path.1'=>1, 'pos' => 1));
        $this->render('post-an-ad-category');
    }


    public function geocodeAction()
    {
        if ($this->_request->isPost()) {
            $listing = Model_Listing_Preview::find($_POST['id']);
            $preview = true;
            if (empty($listing)) {
                $listing = Model_Listing::find($_POST['id']);
                $preview = false;
            }

            if (empty($listing->latitude)) {
                $listing->latitude = $_POST['latitude'];
            }
            if (empty($listing->longitude)) {
                $listing->longitude = $_POST['longitude'];
            }
            if (!$preview) {
                $listing->save();
            }
        }
        exit;
    }

    public function deletePhotoAction() {
        //$listing = Model_Listing::find($_POST['adid']);
        $listing = Model_Listing_Preview::find(new MongoId($_POST['adid']));
        if (empty($listing)) {
            $listing = Model_Listing::find(new MongoId($_POST['adid']));
        }
        if (!empty($listing->user->_id) && (string)$this->loggedin_user->_id != (string)$listing->user->_id)  {
            echo 'nok';
            exit;
        }
        $photos = $listing->photos;
        unset($photos[$_POST['num']]);
        $photos = array_values($photos);
        $listing->photos = $photos;
        if (!empty($listing->photos_tmp)) {
            $photos = $listing->photos_tmp;
            unset($photos[$_POST['num']]);
            $photos = array_values($photos);
            $listing->photos_tmp = $photos;
        }
        $listing->save();
        echo 'ok';
        exit;
    }

    public function featurePhotoAction() {
        //$listing = Model_Listing::find($_POST['adid']);
        $listing = Model_Listing_Preview::find(new MongoId($_POST['adid']));
        if (empty($listing)) {
            $listing = Model_Listing::find(new MongoId($_POST['adid']));
        }
        if (!empty($listing->user->_id) && (string)$this->loggedin_user->_id != (string)$listing->user->_id)  {
            echo 'nok';
            exit;
        }
        $photos = $listing->photos;
        //unset($photos[$_POST['num']]);
        $listing->featured_photo_id = (int)$_POST['id'];
        $photos = array_values($photos);
        $listing->photos = $photos;
        $listing->save();
        echo 'ok';
        exit;
    }

    public function publishAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string)$this->loggedin_user->_id != (string)$ad->user->_id)  {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error'=>'not-allowed')));
        }
        $ad->publish();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) { $tab = $_GET['tab'];} else {$tab = 1;}
        $this->_redirect('/user/my-account-ads?ac=publish&nb=1&tab='.$tab);
    }

    public function unpublishAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string)$this->loggedin_user->_id != (string)$ad->user->_id)  {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error'=>'not-allowed')));
        }

        $ad->unpublish();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) { $tab = $_GET['tab'];} else {$tab = 1;}
        $this->_redirect('/user/my-account-ads?ac=unpublish&nb=1&tab='.$tab);
    }

    public function renewAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string)$this->loggedin_user->_id != (string)$ad->user->_id)  {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error'=>'not-allowed')));
        }

        $ad->renew();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) { $tab = $_GET['tab'];} else {$tab = 1;}
        $this->_redirect('/user/my-account-ads?ac=renew&nb=1&tab='.$tab);
    }

    public function deleteAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string)$this->loggedin_user->_id != (string)$ad->user->_id)  {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error'=>'not-allowed')));
        }

        $ad->deleteListing();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) { $tab = $_GET['tab'];} else {$tab = 1;}
        $this->_redirect('/user/my-account-ads?ac=delete&nb=1&tab='.$tab);
    }

    public function markAsSoldAction()
    {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string)$this->loggedin_user->_id != (string)$ad->user->_id)  {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error'=>'not-allowed')));
        }

        $ad->markAsSold();
        $this->_redirect($this->view->geturl('my-account-ads', 'user'));
    }
}

